/*
 * Copyright 2015 泛泛o0之辈
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jfast.framework.web.core;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jfast核心过滤器
 */
public class ApiFilter extends ApplicationContext implements Filter {

    /** 不处理的请求后缀名 */
    private static List<String> excludeList = new ArrayList<String>();

    /** 应用HTTP地址长度 */
    private int APP_HOST_PATH_LENGTH;

    /**
     * 系统初始化
     * @param filterConfig
     * @throws ServletException
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        getHostPathLength(filterConfig);
        super.loadContext();
    }

    /**
     * 过滤Http请求
     * @param req
     * @param resp
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        if (!handlerResource(getResourceRoute(request), request, response)
                    && !handlerApi(getApiRoute(request), request, response))
                 chain.doFilter(request, response);
    }

    /**
     * 获得Api请求路径
     * @param request
     * @return
     */
    private String getApiRoute(HttpServletRequest request) {
        String uri = request.getRequestURI().substring(APP_HOST_PATH_LENGTH);
        if (uri.indexOf(".") != -1)
            uri = uri.substring(0, uri.indexOf("."));
        return uri;
    }

    /**
     * 获得请求资源路径
     * @param request
     * @return
     */
    private String getResourceRoute(HttpServletRequest request) {
        return request.getRequestURI().substring(APP_HOST_PATH_LENGTH);
    }

    /**
     * 获得应用基地址长度
     * @param filterConfig
     */
    private void getHostPathLength(FilterConfig filterConfig) {
        String contextPath = filterConfig.getServletContext().getContextPath();
        APP_HOST_PATH_LENGTH = (contextPath == null || "/".equals(contextPath) ? 0
                : contextPath.length());
    }

    /**
     * 系统销毁方法
     */
    public void destroy() {
        super.destroy();
    }

}
